/**
 * 输入框失焦时去除两边空格
 * <el-input v-model="xxx" v-trim></el-input>
 */

function getInput(el) {
  let inputEle;
  const {
    tagName
  } = el;
  if (tagName === "INPUT" || tagName === "TEXTAREA") {
    inputEle = el;
  } else {
    inputEle = el.querySelector("input");
    if (!inputEle) {
      inputEle = el.querySelector("textarea");
    }
  }
  return inputEle;
}

function dispatchEvent(el, type) {
  const evt = new Event(type, { bubbles: true, cancelable: true });
  el.dispatchEvent(evt);
}

const directiveTrim = app => {
  app.directive('trim', {
    mounted: el => {
      if (!el) return;
      const inputEle = getInput(el);
      const handler = function (event) {
        if (event.target.value) {
          const newVal = event.target.value.trim();
          if (event.target.value != newVal) {
            event.target.value = newVal;
            dispatchEvent(inputEle, "input");
          }
        }
      };
      el.inputEle = inputEle;
      el._blurHandler = handler;
      inputEle?.addEventListener("blur", handler);
    },
    beforeUnmount(el) {
      const {
        inputEle
      } = el;
      inputEle?.removeEventListener("blur", el._blurHandler);
    }
  });
};
export default directiveTrim;